#!/usr/bin/env bash

########################### FUNCTIONS #############################

### databasefile
dbfile(){
echo -e "\n*********** CHOOSE OR LOAD DATABASE FILE ************"
find db_[0-9]*.db > /dev/null 2>&1
if [ $? -ne 0 ];then
	echo "loading "$1
	cat $1 |  awk -F" " '{print $1"-"$3,$1,$2,$4,$5,$3}' | sort -t' ' -k1,1 > "db_"$datefile".txt" #sort 1000G database file by chromosome and position
	db="db_"$datefile".txt"
else
	echo -e "\ndatabase(s) file(s) in your directory : "
	find db_[0-9]*.db
	echo -e "\nenter database filename to use or press \"c\" to load database's parameter's file"
	read choice2
	if [ "$choice2" == "c" ];then
		echo "loading "$1
		cat $1 |  awk -F" " '{print $1"-"$3,$1,$2,$4,$5,$3}' | sort -t' ' -k1,1 > "db_"$datefile".txt" #sort 1000G database file by chromosome and position
		db="db_"$datefile".txt"
	else
		db=$choice2
	fi
fi
}

############################# MAIN ################################

###check for parameters' number
if [ $# -lt 3 ];then
	echo -e "\nERROR : create_bimfile_to_impute <date_liftoverfiles> <databasefile> <newbimfile>\n" 1>&2
	exit 1
fi

datelift=$1
shift

datefile=`date +%m%e%Y` # date mmddyyyy

### choose or load dbfile
dbfile $1
shift

### create output directory if it doesn't exist yet
if [ ! -d "./newbim_to_impute" ]; then
	mkdir newbim_to_impute
fi

for f in $@;do
	echo -e "\nFILE : $f " 
	name1=${f#newbimfile}
	name2=${name1%%.*}
	echo "headerTodel" > "tmpnewbim_to_impute"$name2"_"$datefile".txt"
	# check existence of newbimfile
	if [ ! -f  $f ];then
		echo "file : $f doesn't exist"
	else
		while read line
		do   
			while IFS="	" read chr snpID genetic_distance bpposition a0 a1
			do
					# check existence of liftoverfile
					if [ ! -f  "output_liftoversh/keeprs_liftover_wellconverted"$name2"_"$datelift".txt" ];then
						echo "$chr	$snpID	$genetic_distance	$bpposition	$a0	$a1" >> "tmpnewbim_to_impute"$name2"_"$datefile".txt"
					else
						keeprs=0 # boolean
						keepchrpos=0 # boolean
						# check snpID  to match with database
						while read keeprsline #rsID different in database
						do
							while IFS=" " read rsIDdata rsIDdb
							do
								if [ $snpID == $rsIDdata ];then
									newbppos=`grep $rsIDdb "$db" | cut -d" " -f1 | sed 's/[0-9]*-//'`
									echo "$chr	$rsIDdb	$genetic_distance	$newbppos	$a0	$a1" >> "tmpnewbim_to_impute"$name2"_"$datefile".txt"
									keeprs=1
								fi
							done
						done < "output_liftoversh/keeprs_liftover_wellconverted"$name2"_"$datelift".txt"
						if [ $keeprs -ne 1 ];then
							while read keepchrposline #rsID identify by chromosome-position in database
							do
								while IFS="	" read chrpos IDdata freqdba0 freqdataa0 deltafreq
								do
									if [ $snpID == $IDdata ];then
										newbppos=`grep $chrpos "$db" | cut -d" " -f1 | sed 's/[0-9]*-//'`
										echo "$chr	$chrpos	$genetic_distance	$newbppos	$a0	$a1" >> "tmpnewbim_to_impute"$name2"_"$datefile".txt"
										keepchrpos=1
									fi				
								done
							done < "output_liftoversh/keepchrpos_liftover_wellconverted"$name2"_"$datelift".txt"	
						fi	
						if [ $keepchrpos -ne 1 ] && [ $keeprs -ne 1 ];then
							echo "$chr	$snpID	$genetic_distance	$bpposition	$a0	$a1" >> "tmpnewbim_to_impute"$name2"_"$datefile".txt"
						fi
					fi
			done
		done < $f	
	fi
	grep -v "headerTodel" "tmpnewbim_to_impute"$name2"_"$datefile".txt" > "newbim_to_impute/newbim_to_impute"$name2"_"$datefile".txt"
	echo -e "see  newbim_to_impute/newbim_to_impute"$name2"_"$datefile".txt"
done

rm tmpnew*

# command example : ./create_bimfile_to_impute.sh 07262011 ../../db/NEW_1000/EUR.chrfulldata.db newbimfile_*


	# pour chaque ligne
		# verifier si un liftover a déjà été fait
		# verification du rs 
			# est-ce qu'il existe dans keeprs(colonne1) (grep dev/null et $?) => si oui : remplacer ce champ par la colonne 2 (on créer un deuxième fichier à la volée)
			# elsif => si non : est-ce qu'il existe dans keepchrpos(colonne2) => si oui le remplacer par la colonne 1
			# else remettre le mm rs
			# chercher la position dans la base de données en utilisant un grep de rsdata(nouvellement mis à jour juste avant) sur rsbd et en récupérant le 3 ème champ
			# mettre dans le newbimfile : chr(du newbim), rs(nouveau), genetic distance(du newbim), bp(des 1000G) et a0 a1(du newbim)  
			# keep fiedls : chr, snpID, genetic distance, a0 and a1 from newbimfile ($f)
	# fin pour
	# bimtoimpute créé !
